<template>
  <container-item-wrapper :widget="widget">
    <vxe-toolbar>
      <template v-if="!isReadMode" #buttons>
        <el-button v-if="widget.options.add" type="primary" @click="insertEvent()">{{
          i18nt('designer.setting.operateAdd') }}</el-button>
        <el-button v-if="widget.options.delete" @click="removeSelectRows()">{{ i18nt('designer.setting.operateDelete')
        }}</el-button>
        <el-button v-if="widget.options.import" @click="importData()">{{ i18nt('designer.setting.operateImport')
        }}</el-button>
        <el-button v-if="widget.options.export" @click="exportData()">{{ i18nt('designer.setting.operateExport')
        }}</el-button>
        <el-button v-if="widget.options.refresh" @click="refresh()">{{ i18nt('designer.setting.operateRefresh')
        }}</el-button>
        <el-button @click="openLPDialog" v-if="widget.options.name === 'lifeStatesDataTable'">获取物料</el-button>
        <el-button @click="openStateModal" v-if="widget.options.name === 'lifeStatesDataTable'">修改状态</el-button>
        <el-dialog title="选择物料状态" v-model="stateModalVisible" width="500px" :before-close="handleModalClose"
          :close-on-click-modal="false">
          <div class="state-modal-content">
            <!-- <p class="modal-description">请选择要修改的目标状态：</p> -->

            <!-- 状态选择表格（使用el-table） -->
            <el-table ref="stateTable" :data="stateOptions" border size="mini" @row-click="handleRowClick"
              :row-class-name="getRowClassName" row-key="id" style="width: 100%;">
              <el-table-column width="300" prop="id" label="内部名称" align="left"></el-table-column>
              <el-table-column prop="name" label="状态名称" align="left"></el-table-column>
            </el-table>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button @click="handleModalClose">取消</el-button>
            <el-button type="primary" @click="confirmStateChange">确认</el-button>
          </div>
        </el-dialog>


        <el-button v-if="yjshow && (widget.options.name === 'datatable67262')"
          @click="obtainCostInformation('硬件')">获取成本信息</el-button>

        <el-button v-if="yjshow && (widget.options.name === 'datatable70276')"
          @click="obtainCostInformation('硬件')">获取成本信息</el-button>

        <el-button v-if="RJSHow && (widget.options.name === 'datatable37383')"
          @click="obtainCostInformation('结构')">获取成本信息</el-button>

        <el-button v-if="yjshow && (widget.options.name === 'datatable67262')"
          @click="totalCostTotalCost('硬件')">成本合计</el-button>

        <el-button v-if="yjshow && (widget.options.name === 'datatable70276')"
          @click="totalCostTotalCost('硬件')">成本合计</el-button>

        <el-button v-if="RJSHow && (widget.options.name === 'datatable37383')"
          @click="totalCostTotalCost('结构')">成本合计</el-button>
        <el-button v-if="this.widget.options.name === 'requisition'" @click="priceCost('结构')">金额计算</el-button>
        <el-button @click="openMaterial('送货地址')" v-if="widget.options.name === 'requisition'">送货地址</el-button>
        <el-button @click="openMaterial('存储地点_深圳')" v-if="widget.options.name === 'requisition'">存储地点_深圳</el-button>
        <el-button @click="openMaterial('存储地点_惠州')" v-if="widget.options.name === 'requisition'">存储地点_惠州</el-button>
        <el-button @click="openDialog('需求数量')" v-if="widget.options.name === 'requisition'">需求数量</el-button>
        <el-button @click="openDialog('单价')" v-if="widget.options.name === 'requisition'">单价</el-button>
        <el-button @click="openDialog('小计金额')" v-if="widget.options.name === 'requisition'">小计金额</el-button>
        <el-button @click="openDateModal('需求日期')" v-if="widget.options.name === 'requisition'">需求日期</el-button>
        <!-- 地址弹窗 -->
        <el-dialog :title="materialTitle" v-model="materialVisible" width="500px" :before-close="handleMaterialClose"
          :close-on-click-modal="false">
          <div class="state-modal-content">
            <el-table ref="materialTable" :data="materialOptions" border size="mini" @row-click="handleMaterialRowClick"
              :row-class-name="getMaterialRowClassName" row-key="id" style="width: 100%;">
              <el-table-column width="300" prop="id" label="序号" align="left"></el-table-column>
              <el-table-column prop="name" label="地点" align="left"></el-table-column>
            </el-table>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button @click="handleMaterialClose">取消</el-button>
            <el-button type="primary" @click="confirmMaterialChange(materialTitle)">确认</el-button>
          </div>
        </el-dialog>
        <!-- 输入框弹窗 -->
        <el-dialog :title="modalTitle" v-model="isInputVisible" :before-close="handleInputClose" :width="'400px'"
          :close-on-click-modal="false">
          <div class="modal-content">
            <p style="margin-top: -30px;">请输入{{ currentField }}</p>

            <el-input v-model="inputValue" placeholder="请输入内容" class="input-field"></el-input>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="handleInputClose">
              取消
            </el-button>
            <el-button type="primary" @click="handleInputConfirm(modalTitle)">
              确定
            </el-button>
          </div>
        </el-dialog>

        <!-- 日期弹窗 -->
        <el-dialog :title="DateTitle" v-model="isDateVisible" :before-close="handleDateClose" :width="'400px'"
          :close-on-click-modal="false">
          <div class="modal-content">
            <el-date-picker v-model="selectedDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"></el-date-picker>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="handleDateClose">
              取消
            </el-button>
            <el-button type="primary" @click="handleDateConfirm">
              确定
            </el-button>
          </div>
        </el-dialog>

        <!-- 料品生命状态变更表弹窗 -->
        <el-dialog title="选择对象" v-model="LPdialogVisible" :width="dialogWidth" :before-close="handleLPClose"
          :close-on-click-modal="false">
          <!-- 搜索区域 -->
          <div class="search-container">
            <el-input v-model="searchKeyword" placeholder="请输入关键词" clearable style="width: 300px; margin-right: 10px;">
            </el-input>
            <el-button type="primary" @click="handleLPSearch">搜索</el-button>
            <el-button @click="handleLPRefresh">刷新</el-button>
          </div>

          <!-- 表格区域 -->
          <el-table ref="multipleTable" :data="LPtableData" border style="width: 100%; margin-top: 15px;"
            @selection-change="handleLPSelectionChange" max-height="400px">

            <!-- 多选列 -->
            <el-table-column type="selection" width="55">
            </el-table-column>

            <!-- 表格列 -->
            <el-table-column prop="partNumber" label="编号" width="120">
            </el-table-column>
            <el-table-column prop="partName" label="名称" width="200">
            </el-table-column>
            <el-table-column prop="specs" label="规格">
            </el-table-column>
            <el-table-column prop="lifeStatesPerson" label="料品生命状态负责人" width="140">
            </el-table-column>
            <el-table-column prop="stock" label="质控等级" width="100">
            </el-table-column>
            <el-table-column prop="lifeStates" label="料品生命状态" width="120">
            </el-table-column>
          </el-table>

          <!-- 分页区域 -->
          <div class="pagination-container" style="margin-top: 15px; text-align: right;">
            <el-pagination @size-change="handleLPSizeChange" @current-change="handleLPCurrentChange"
              :current-page="LPcurrentPage" :page-sizes="[20, 50, 100]" :page-size="LPpageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="LPtotal">
            </el-pagination>
          </div>

          <!-- 弹窗底部按钮 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="handleLPClose">取消</el-button>
            <el-button type="primary" @click="handleLPConfirm">确定</el-button>
          </span>
        </el-dialog>


        <!-- 采购变更供应商选择弹窗 -->
        <el-dialog title="选择供应商" v-model="CGBGdialogVisible" :width="dialogWidth" :before-close="handleCGBGClose"
          :close-on-click-modal="false">
          <!-- 搜索区域 -->
          <div class="search-container">
            <el-input v-model="CGBGsearchKeyword" placeholder="请输入关键词" clearable
              style="width: 300px; margin-right: 10px;">
            </el-input>
            <el-button type="primary" @click="handleCGBGSearch">搜索</el-button>
            <!-- <el-button @click="handleLPRefresh">刷新</el-button> -->
          </div>

          <!-- 表格区域 -->
          <el-table ref="CGBGmultipleTable" :data="CGBGtableData" border style="width: 100%; margin-top: 15px;"
            @row-click="handleCGBGRowClick" max-height="400px" highlight-current-row>
            <!-- 多选列 -->
            <!-- <el-table-column type="selection" width="55">
            </el-table-column> -->
            <!-- 表格列 -->
            <el-table-column label="序号" type="index" width="300" align="center">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="displayName" label="供应商" align="center">
            </el-table-column>
          </el-table>

          <!-- 分页区域 -->
          <div class="pagination-container" style="margin-top: 15px; text-align: right;">
            <el-pagination @size-change="handleCGBGSizeChange" @current-change="handleCGBGCurrentChange"
              :current-page="CGBGcurrentPage" :page-sizes="[20, 50, 100]" :page-size="CGBGpageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="CGBGtotal">
            </el-pagination>
          </div>

          <!-- 弹窗底部按钮 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="handleCGBGClose">取消</el-button>
            <el-button type="primary" @click="handleCGBGConfirm">确定</el-button>
          </span>
        </el-dialog>

      </template>
    </vxe-toolbar>
    <vxe-grid ref="xGrid" v-bind="gridOptions" :columns="columns" row-class-name="data-table-widget-row"
      class="data-table-item" :stripe="widget.options.stripe" :height="tableHeight" :footer-method="footerMethod"
      :style="{ width: this.widget.options.tableWidth || '100%' }" :show-footer="widget.options.showSummary"
      @edit-closed="handleEditClosed" @cell-click="handleCellClick">
      <template #pager v-if="widget.options.showPagination">
        <vxe-pager :layouts="widget.options.smallPagination ? ['PrevPage', 'Number', 'NextPage'] : ['Total', 'PrevPage', 'Number', 'PageCount', 'NextPage', 'Sizes', 'FullJump']
          " :current-page="currentPage" :page-size="pageSize" :pageSizes="[5, 10, 20, 50, 100]"
          :total="gridOptions.data.length" :align="widget.options.paginationAlign"
          @page-change="handleCurrentPageChange"></vxe-pager>
      </template>
    </vxe-grid>
    <select-object-dialog v-model="showDialog" :field="widget" @confirm="confirmFunc" />
  </container-item-wrapper>
</template>

<script lang="jsx">
import formDesigner from '@common/form-designer';
import { request } from '@common/core';
import tyUi from '@common/ty-ui';

import axios from 'axios';
const { TyPlmInput } = tyUi.getExportResource('src/ty-ui/lib/ty-input/index.js');
const { TyPlmTimeDate } = tyUi.getExportResource('src/ty-ui/lib/ty-time-date/index.js');
const { TyPlmSelect } = tyUi.getExportResource('src/ty-ui/lib/ty-select/index.js');
const FormItemWrapper = formDesigner.getExportResource('src/form-designer/extension/form-render/data-table-item.vue');
export default {
  extends: FormItemWrapper.default,
  data() {
    return {
      iscounted: false,
      //采购变更
      CGBGdialogVisible: false,
      CGBGdialogVisible: false,
      CGBGsearchKeyword: '',
      CGBGtableData: [],     //当前页展示的数据
      allCGBGtableData: [], // 从接口获取的所有原始数据
      originalCGBGtableData: [], // 用于存储原始数据，供搜索和刷新使用
      CGBGRowData: null,    // 记录是从哪一行点击的
      CGBGmultipleSelection: [],
      CGBGcurrentPage: 1,
      CGBGpageSize: 20,
      CGBGtotal: 0, // 总条数,
      CGBGflag: false,
      currentCGBGRowData: null,

      //料品生命变更
      LPdialogVisible: false,
      dialogWidth: '80%',
      searchKeyword: '',
      LPtableData: [],     //当前页展示的数据
      allLPtableData: [], // 从接口获取的所有原始数据
      originalLPtableData: [], // 用于存储原始数据，供搜索和刷新使用
      LPmultipleSelection: [],
      LPcurrentPage: 1,
      LPpageSize: 20,
      LPtotal: 0, // 总条数,
      LPflag: false,


      isDateVisible: false,
      DateTitle: '选择日期',
      selectedDate: '', // 用于存储选中的日期

      isInputVisible: false,   // 输入框弹窗
      modalTitle: '',
      currentField: '',
      inputValue: '',

      materialTitle: '',
      materialVisible: false,    // 物料弹窗
      enableCompute: false, // 默认关闭，操作后开启
      materialOptions: [],
      materialRowId: '',
      materialName: '',
      showDialog: false,
      selectAllFlag: false,
      selectedRows: [],  // 存储勾选的物料行
      currentPage: 1,
      pageSize: 10,
      columns: [],
      yjshow: false,
      RJSHow: false,
      stateModalVisible: false, // 生命周期弹窗显示状态
      checkedRowId: '',  //当前行ID
      checkedName: '',
      stateOptions: [ // 状态选项数据
        { id: '01', name: '正常' },
        { id: '02', name: '停产' },
        { id: '03', name: '同类优选' },
        { id: '04', name: '呆滞' },
        { id: '05', name: '不推荐' },
        { id: '06', name: '耗尽停产' },
        { id: '07', name: '引入期' },
        { id: '08', name: '成长期' },
        { id: '09', name: '成熟期' },
        { id: '10', name: '衰退期' }
      ],
    };
  },

  watch: {
    // modify by nieyz 2024/10/22 业务规则设置表格只读时重置表单列形态
    'widget.options.readonly': {
      handler(val) {
        console.log('adada')
        this.makeColumns();
      }
    }
  },
  mounted() {
    console.log("mingzi", this.widget.options.name)
    if (this.widget.options.name == 'datatable25710') {
      console.log("获取枚举")
      this.getCGBGData()
    }
    // modify by caoy 2025/03/11 v3表单加载完成获取数据
    this.$on('initBiaoDan', this.initBiaoDan);
  },
  methods: {
    //采购变更
    async getCGBGData() {
      const res = await request({
        method: 'post',
        url: '/rest/v1/enum/queryEnumerationItemByDefOid',
        headers: {
          authorization: sessionStorage.getItem('authorization'),
          // 'Content-Type': 'application/json',
        },
        data: {
          oid: '733446807635804160'
        }
      });
      console.log('resData', res)
      this.allCGBGtableData = res.data.data;
      // 保存原始数据用于搜索
      this.originalCGBGtableData = res.data.data;
      // 当前数据也初始化为全部数据
      this.allCGBGtableData = this.originalCGBGtableData;
      this.CGBGtotal = this.allCGBGtableData.length;
      this.handleCGBGPagination();   // 分页方法
    },
    handleCGBGPagination() {    // 分页方法
      // 计算当前页数据的起始索引和结束索引
      const startIndex = (this.CGBGcurrentPage - 1) * this.CGBGpageSize;
      const endIndex = startIndex + this.CGBGpageSize;
      // 从所有原始数据中截取当前页数据
      this.CGBGtableData = this.allCGBGtableData.slice(startIndex, endIndex);
    },
    handleCGBGSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.CGBGpageSize = val;
      this.CGBGcurrentPage = 1;
      this.handleCGBGPagination();
    },
    handleCGBGCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.CGBGcurrentPage = val;
      this.handleCGBGPagination();
    },
    handleCGBGSearch() {   //搜索框
      console.log('搜索')
      // 如果搜索关键词为空，显示所有数据
      if (!this.CGBGsearchKeyword) {
        this.allCGBGtableData = this.originalCGBGtableData || this.allCGBGtableData;
      } else {

        const keyword = this.CGBGsearchKeyword.toLowerCase();
        this.allCGBGtableData = this.originalCGBGtableData.filter(item => {
          // 只检查displayName是否包含关键词
          return item.displayName.toLowerCase().includes(keyword);
        });
      }
      // 重置分页并重新计算当前页数据
      this.CGBGcurrentPage = 1;
      this.CGBGtotal = this.allCGBGtableData.length;
      this.handleCGBGPagination();
    },
    handleCGBGRowClick(row, event, column) {
      console.log('当前行数据:', row);
      this.currentCGBGRowData = row;
    },
    handleCGBGConfirm() {
      if (this.currentCGBGRowData == null) {
        this.$message({
          message: '请选择一家供应商',
          type: 'warning',
          zIndex: 9999 // 单独指定z-index
        })
        return;
      }
      console.log('确认选择:', this.currentCGBGRowData);
      const $table = this.$refs.xGrid;
      if (!$table) {
        // this.$message.error('表格未加载完成，请稍后再试');
        this.$message({
          message: '表格未加载完成，请稍后再试',
          type: 'error',
          zIndex: 9999 // 单独指定z-index
        })
        return;
      }
      let displayName = this.currentCGBGRowData.displayName
      console.log('数据', displayName)
      this.CGBGRowData.main_supplier = displayName
      // 插入数据
      // $table.insertAt(tableData, -1);
      this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
      this.$message({
        message: '成功选择供应商',
        type: 'success',
        zIndex: 9999 // 单独指定z-index
      })
      this.CGBGsearchKeyword = ''
      this.currentCGBGRowData = null
      this.CGBGdialogVisible = false;
    },
    handleCGBGClose() {    //弹窗关闭  
      this.CGBGdialogVisible = false
    },
    handleCellClick({ row, column, cell }) {    //点击单元格时开启弹窗
      console.log('row', row)
      this.CGBGRowData = row
      console.log('column', column)
      console.log('$cell', cell)
      if (column.field == 'main_supplier') {
        this.CGBGdialogVisible = true
      }

    },


    //物料需求
    openStateModal() {    //物料生命状态修改
      const grid = this.$refs.xGrid;
      if (!grid) return;
      const selectedRows = grid.getCheckboxRecords();
      if (selectedRows.length === 0) {
        this.$message.warning("请先勾选需要修改的物料！");
        return;
      }
      this.checkedName = ''
      this.checkedRowId = ''
      this.stateModalVisible = true
    },
    openDialog(field) {
      const grid = this.$refs.xGrid;
      if (!grid) return;
      const selectedRows = grid.getCheckboxRecords();
      if (selectedRows.length === 0) {
        this.$message.warning("请先勾选需要修改的物料！");
        return;
      }
      this.currentField = field;
      // 设置标题，这里使用字段名作为标题，也可以根据需要映射为其他名称
      this.modalTitle = field;
      // 清空输入框
      this.inputValue = '';
      // 显示弹窗
      this.isInputVisible = true;
    },

    openMaterial(val) {
      this.materialTitle = val

      if (val == '送货地址') {
        let data = [ // 状态选项数据
          { id: '01', name: '惠州' },
          { id: '02', name: '深圳A栋' },
          { id: '03', name: '深圳4栋' }
        ]
        this.materialOptions = data
      } else if (val == '存储地点_深圳') {
        let data = [ // 状态选项数据
          { id: '01', name: '原材料仓' },
          { id: '02', name: '半成品仓' },
          { id: '03', name: '成品仓' },
          { id: '04', name: '呆滞仓' },
          { id: '05', name: '报废仓' },
          { id: '06', name: '客供仓' },
          { id: '07', name: '不良品仓' },
          { id: '08', name: '成品仓（惠州）' },
          { id: '09', name: '协同委外仓' },
          { id: '10', name: 'SMT原料仓' },
          { id: '11', name: '前置加工一仓' },
          { id: '12', name: '前置加工二仓' },
          { id: '13', name: '焊接加工一仓' },
          { id: '14', name: '焊接加工二仓' },
          { id: '15', name: '车间原料一仓' },
          { id: '16', name: '车间原料二仓' },
          { id: '17', name: '线材车间原料仓' },
          { id: '18', name: 'SMT前置加工仓' }
        ]
        this.materialOptions = data
      } else {
        let data = [ // 状态选项数据
          { id: '01', name: '原材料仓' },
          { id: '02', name: '半成品仓' },
          { id: '03', name: '成品仓' },
          { id: '04', name: '呆滞仓' },
          { id: '05', name: '报废仓' },
          { id: '06', name: '客供仓' },
          { id: '07', name: '不良品仓' },
          { id: '08', name: '注塑原料仓' },
          { id: '09', name: '机加原料仓' },
          { id: '10', name: '电机原料仓' },
          { id: '11', name: '前段定子仓' },
          { id: '12', name: '后段定子仓' },
          { id: '13', name: '转子仓' },
          { id: '14', name: '机加委外半成品仓' },
          { id: '15', name: '车铣仓' },
          { id: '16', name: '电控原料仓' },
          { id: '17', name: '焊接组装仓' },
          { id: '18', name: '前置加工仓' },
          { id: '19', name: '线材车间原料仓' }
        ]
        this.materialOptions = data
      }
      const grid = this.$refs.xGrid;
      if (!grid) return;
      const selectedRows = grid.getCheckboxRecords();
      if (selectedRows.length === 0) {
        this.$message.warning("请先勾选需要修改的物料！");
        return;
      }
      // 重置弹窗状态
      this.materialRowId = '';
      this.materialName = ''

      this.materialVisible = true

    },
    openDateModal() {
      const grid = this.$refs.xGrid;
      if (!grid) return;
      const selectedRows = grid.getCheckboxRecords();
      if (selectedRows.length === 0) {
        this.$message.warning("请先勾选需要修改的物料！");
        return;
      }
      this.selectedDate = '';
      // 显示弹窗
      this.isDateVisible = true;
    },
    getMaterialRowClassName({ row }) {
      // 确保比较时类型一致
      if (String(row.id) === String(this.materialRowId)) {
        return 'highlight-row';
      }
      return '';
    },

    getRowClassName({ row }) {
      // 确保比较时类型一致
      if (String(row.id) === String(this.checkedRowId)) {
        return 'highlight-row';
      }
      return '';
    },
    handleMaterialRowClick(row) {
      this.materialRowId = String(row.id);
      this.materialName = row.name
      this.$nextTick(() => {
        if (this.$refs.stateTable) {
          this.$refs.stateTable.clearSelection();
          this.$refs.stateTable.toggleRowSelection(row, true);
        }
      });
    },
    handleRowClick(row) {
      console.log('row', row)
      this.checkedName = row.name
      this.checkedRowId = row.id
      // if (this.$refs.stateTable) {
      //   this.$refs.stateTable.clearSelection();
      // }
      // this.$nextTick(() => {
      //   this.stateModalVisible = false
      // });
    },
    //物料修改
    confirmMaterialChange(val) {
      const grid = this.$refs.xGrid;
      if (!grid) return;
      if (this.materialRowId == '') {
        this.$message.warning("请选择一个地址！");
        return;
      }
      // 显式获取当前选中行
      const selectedRows = grid.getCheckboxRecords();
      const selectedState = this.materialName;
      if (val == '送货地址') {
        selectedRows.forEach(row => {
          // 更新字段值（直接修改行数据）
          row.shdz = selectedState;
        });
      } else if (val == '存储地点_深圳') {
        selectedRows.forEach(row => {
          // 更新字段值（直接修改行数据）
          row.ccdd_sz = selectedState;
        });
      } else if (val == '存储地点_惠州') {
        selectedRows.forEach(row => {
          // 更新字段值（直接修改行数据）
          row.ccdd_hz = selectedState;
        });
      }


      // 3. 同步更新表单模型（确保保存时能获取到最新数据）
      this.globalModel.formModel[this.widget.options.name] = grid.getTableData()?.fullData || [];

      // 4. 提示成功
      this.$message.success(`已将物料的“${val}”修改为：${selectedState}`);
      // 检查是否选择了状态
      this.materialVisible = false;
      this.materialName = ''
      this.materialRowId = ''

    },
    // 确认状态修改
    confirmStateChange(val) {
      const grid = this.$refs.xGrid;
      if (!grid) return;
      if (this.checkedRowId == '') {
        this.$message.warning("请选择一个目标状态！");
        return;
      }
      // 显式获取当前选中行
      const selectedRows = grid.getCheckboxRecords();
      // 获取选中的状态
      const selectedState = this.checkedName;
      selectedRows.forEach(row => {
        // 更新字段值（直接修改行数据）
        row.update_lifeStates = selectedState;
        // 刷新表格行，确保视图同步更新

      });

      // 3. 同步更新表单模型（确保保存时能获取到最新数据）
      this.globalModel.formModel[this.widget.options.name] = grid.getTableData()?.fullData || [];

      // 4. 提示成功
      this.$message.success(`已将物料的“料品生命状态(变更后)”修改为：${selectedState}`);
      // 检查是否选择了状态
      this.stateModalVisible = false;
      this.checkedRowId = ''

    },

    handleDateConfirm() {     //日期确认
      const grid = this.$refs.xGrid;
      if (!grid) return;
      if (this.selectedDate == '') {
        this.$message.warning("请选择一个日期！");
        return;
      }
      const selectedRows = grid.getCheckboxRecords();
      // 获取选中的状态
      const selectedState = this.selectedDate;
      console.log('asd', selectedState)
      selectedRows.forEach(row => {
        // 更新字段值（直接修改行数据）
        row.date = selectedState;
        console.log('row.date', row.date)
        // 刷新表格行，确保视图同步更新

      });

      // 3. 同步更新表单模型（确保保存时能获取到最新数据）
      this.globalModel.formModel[this.widget.options.name] = grid.getTableData()?.fullData || [];

      // 4. 提示成功
      this.$message.success(`已将物料的“需求日期”修改为：${selectedState}`);
      // 检查是否选择了状态
      this.isDateVisible = false;
      this.selectedDate = ''
    },
    handleInputConfirm(val) {
      const grid = this.$refs.xGrid;
      if (!grid) return;
      if (this.inputValue == '') {
        this.$message.warning("请输入内容！");
        return;
      }
      const selectedRows = grid.getCheckboxRecords();
      // 获取选中的状态
      const selectedState = this.inputValue;
      if (val == '需求数量') {
        selectedRows.forEach(row => {
          // 更新字段值（直接修改行数据）
          row.xqsl = selectedState;
        });
      } else if (val == '单价') {
        selectedRows.forEach(row => {
          // 更新字段值（直接修改行数据）
          row.unitPrice = selectedState;
        });
      } else if (val == '小计金额') {
        selectedRows.forEach(row => {
          // 更新字段值（直接修改行数据）
          row.moneyall = selectedState;
        });
      }

      // 3. 同步更新表单模型（确保保存时能获取到最新数据）
      this.globalModel.formModel[this.widget.options.name] = grid.getTableData()?.fullData || [];

      // 4. 提示成功
      this.$message.success(`已将物料的“${val}”修改为：${selectedState}`);
      // 检查是否选择了状态
      this.isInputVisible = false;
      this.inputValue = ''


    },
    handleMaterialClose() {    //关闭物料地址弹窗
      this.materialName = '';
      this.materialRowId = '',
        this.materialVisible = false;
    },
    handleModalClose() {    //关闭弹窗
      this.checkedRowId = '';
      this.checkedName = '',
        this.stateModalVisible = false;
    },
    handleInputClose() {     //关闭输入弹窗
      this.inputValue = ''
      this.isInputVisible = false
    },
    handleDateClose() {      // 关闭日期选择器弹窗
      this.selectedDate = ''
      this.isDateVisible = false
    },
    // 在组件的methods中添加此方法
    handleLPSelectionChange(val) {
      this.LPmultipleSelection = val;
      console.log('已选择:', this.LPmultipleSelection);
    },
    async getWLData() {
      let userNumber = sessionStorage.getItem('userName')
      // 创建自定义加载框
      const loadingDiv = document.createElement('div');
      loadingDiv.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    flex-direction: column;
    color: white;
    font-size: 16px;
  `;
      // 加载动画（简单的圆形旋转动画）
      const spinner = document.createElement('div');
      spinner.style.cssText = `
    width: 40px;
    height: 40px;
    border: 4px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: white;
    animation: spin 1s ease-in-out infinite;
    margin-bottom: 16px;
  `;
      // 添加动画样式
      const style = document.createElement('style');
      style.textContent = `
    @keyframes spin {
      to { transform: rotate(360deg); }
    }
  `;
      // 加载文本
      const text = document.createTextNode('正在获取物料数据...');
      // 组装加载框
      loadingDiv.appendChild(spinner);
      loadingDiv.appendChild(text);
      document.head.appendChild(style);
      document.body.appendChild(loadingDiv);
      try {
        let res = await axios({
          url: '/rest/v1/formFunction/queryPartByStatusPerson',
          method: 'get',
          params: {
            userNumber,
          },
          headers: {
            authorization: sessionStorage.getItem('authorization')
          },
        })
        console.log('res.data', res.data)
        this.allLPtableData = res.data.data;
        // 保存原始数据用于搜索
        this.originalLPtableData = res.data.data;
        // 当前数据也初始化为全部数据
        this.allLPtableData = this.originalLPtableData;
        this.LPtotal = this.allLPtableData.length;
        this.handlePagination();   // 分页方法
        this.LPdialogVisible = true
        // this.$message.success('获取物料数据成功');
      } catch (error) {
        // this.$message.error('获取物料数据失败，请稍后再试');
        this.$message({
          message: '获取物料数据失败，请稍后再试',
          type: 'error',
          zIndex: 9999 // 单独指定z-index
        })
      } finally {
        // 无论成功失败，都移除加载框
        document.body.removeChild(loadingDiv);
        document.head.removeChild(style);
      }
    },
    handlePagination() {    // 分页方法
      // 计算当前页数据的起始索引和结束索引
      const startIndex = (this.LPcurrentPage - 1) * this.LPpageSize;
      const endIndex = startIndex + this.LPpageSize;
      // 从所有原始数据中截取当前页数据
      this.LPtableData = this.allLPtableData.slice(startIndex, endIndex);
    },
    handleLPSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.LPpageSize = val;
      this.LPcurrentPage = 1;
      this.handlePagination();
    },
    handleLPCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.LPcurrentPage = val;

      this.handlePagination();
    },
    // 确认选择
    handleLPConfirm() {
      if (this.LPmultipleSelection.length === 0) {
        this.$message({
          message: '请至少选择一项',
          type: 'warning',
          zIndex: 9999 // 单独指定z-index
        })
        // this.$message.warning('请至少选择一项');

        return;
      }
      console.log('确认选择:', this.LPmultipleSelection);
      // this.$message.success(`已选择 ${this.LPmultipleSelection.length} 项`);
      const $table = this.$refs.xGrid;
      if (!$table) {
        // this.$message.error('表格未加载完成，请稍后再试');
        this.$message({
          message: '表格未加载完成，请稍后再试',
          type: 'error',
          zIndex: 9999 // 单独指定z-index
        })
        return;
      }
      // $table.clearData(); // 清空表格
      // this.globalModel.formModel[this.widget.options.name] = []; // 同步清空表单模型
      let tableData = this.LPmultipleSelection.map(item => ({
        partNumber: item.partNumber,
        partName: item.partName,
        specs: item.specs,
        lifeStatesPerson: item.lifeStatesPerson,
        stock: item.stock,
        lifeStates: item.lifeStates,
      }));

      // 插入数据
      $table.insertAt(tableData, -1);
      this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
      this.$message({
        message: '添加物料数据成功',
        type: 'success',
        zIndex: 9999 // 单独指定z-index
      })
      // this.$message.success('添加物料数据成功');
      this.LPdialogVisible = false;
    },
    handleLPSearch() {   //搜索框
      console.log('搜索')
      // 如果搜索关键词为空，显示所有数据
      if (!this.searchKeyword) {
        this.allLPtableData = this.originalLPtableData || this.allLPtableData;
      } else {
        // 仅根据partName字段筛选数据
        const keyword = this.searchKeyword.toLowerCase();
        this.allLPtableData = this.originalLPtableData.filter(item => {
          // 只检查partName是否包含关键词
          return item.partNumber.toLowerCase().includes(keyword) || item.partName.toLowerCase().includes(keyword)
            || item.specs.toLowerCase().includes(keyword);
        });
      }

      // 重置分页并重新计算当前页数据
      this.LPcurrentPage = 1;
      this.LPtotal = this.allLPtableData.length;
      this.handlePagination();
    },
    handleLPRefresh() {  //刷新
      // 清空搜索关键词
      this.searchKeyword = '';
      // 恢复原始数据
      this.allLPtableData = this.originalLPtableData;
      // 重置分页
      this.LPcurrentPage = 1;
      this.LPtotal = this.allLPtableData.length;
      this.handlePagination();
    },
    handleLPClose() {
      this.LPdialogVisible = false
    },
    openLPDialog() {
      this.getWLData()
    },

    /**
   * 点击【金额计算】按钮
   * 功能：
   *  1. 计算每行小计金额：moneyall = money * xqsl
   *  2. 校验单价和需求数量是否为空
   *  3. 插入小计金额汇总行
   */
    handleEditClosed({ row, column }) {
      if (column.field == 'cost') {
        // console.log('行与列', row)
        // console.log('llie', column)
        let cost = row.cost
        const $table = this.$refs.xGrid;
        if (!$table) {
          // this.$message.error('表格未加载完成，请稍后再试');
          this.$message({
            message: '表格未加载完成，请稍后再试',
            type: 'error',
            zIndex: 9999 // 单独指定z-index
          })
          return;
        }
        row[column.field] = cost;
        this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
        console.log('表单aa', this.$refs.xGrid.getTableData()?.fullData)
        // console.log('biao',$table.getTableData()?.fullData)
      }
      console.log('enableCompute', this.enableCompute)
      if (!this.enableCompute) {
        return
      }

      // 字段名：column.field
      const modifiedField = column.field;
      console.log("modifiedFiled", modifiedField)
      // 检查是否修改了“单价”或“需求数量”
      if (modifiedField === 'unitPrice' || modifiedField === 'xqsl') {
        this.priceCost1(); // 调用金额计算函数
      }
    },
    priceCost1() {
      const $table = this.$refs.xGrid;
      const tableData = this.$refs.xGrid.getTableData()?.fullData ?? [];
      let dataToCalculate = tableData.slice(0, -1);
      let lastData = tableData.slice(-1)
      let totalMoneyAll = 0;
      const errors = [];

      // 第一步：遍历所有行，计算小计金额并校验
      dataToCalculate.forEach((item, index) => {
        const price = item.unitPrice; // 单价
        const quantity = item.xqsl; // 需求数量

        const priceValid = price != null && price !== '' && !isNaN(parseFloat(price));
        const quantityValid = quantity != null && quantity !== '' && !isNaN(parseFloat(quantity));

        // 如果单价或需求数量无效，记录错误
        if (!priceValid || !quantityValid) {
          errors.push(
            `第 ${index + 1} 行：单价为“${price}”，需求数量为“${quantity}”，请维护有效的单价和需求数量。`
          );
        } else {
          // 计算小计金额
          const moneyall = parseFloat(price) * parseFloat(quantity);
          item.moneyall = parseFloat(moneyall.toFixed(4)); // 保留4位小数，避免浮点误差
          totalMoneyAll += item.moneyall;

        }
      });
      // 第二步：如果有错误，统一提示，不插入汇总行
      if (errors.length > 0) {
        this.$alert(
          `<div style="max-height: 400px; overflow-y: auto; font-size: 14px;">
        <p>以下 ${errors.length} 行数据不完整，无法计算小计金额：</p>
        <ul style="list-style: circle; padding-left: 20px;">
          ${errors.map(err => `<li>${err}</li>`).join('')}
        </ul>
      </div>`,
          '数据维护提示',
          {
            dangerouslyUseHTMLString: true,
            type: 'error',
            center: false,
            confirmButtonText: '确定'
          }
        );
        return;
      }
      lastData[0].moneyall = totalMoneyAll.toFixed(2)
      dataToCalculate = [...dataToCalculate, ...lastData]
      // 第三步：插入汇总行
      if (totalMoneyAll > 0) {


        this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
        this.$message.success(`小计金额合计：${totalMoneyAll.toFixed(2)} 已插入`);
      } else {
        this.$message.warning('小计金额为 0，未插入汇总行。');
      }

    },
    priceCost() {
      const $table = this.$refs.xGrid;
      const tableData = this.$refs.xGrid.getTableData()?.fullData ?? [];
      // const tableData = this.$refs.xGrid.getTableData()?.tableData ?? [];

      let totalMoneyAll = 0;
      const errors = [];

      // 第一步：遍历所有行，计算小计金额并校验
      tableData.forEach((item, index) => {
        const price = item.unitPrice; // 单价
        const quantity = item.xqsl; // 需求数量

        const priceValid = price != null && price !== '' && !isNaN(parseFloat(price));
        const quantityValid = quantity != null && quantity !== '' && !isNaN(parseFloat(quantity));

        // 如果单价或需求数量无效，记录错误
        if (!priceValid || !quantityValid) {
          errors.push(
            `第 ${index + 1} 行：单价为“${price}”，需求数量为“${quantity}”，请维护有效的单价和需求数量。`
          );
        } else {
          // 计算小计金额
          const moneyall = parseFloat(price) * parseFloat(quantity);
          item.moneyall = parseFloat(moneyall.toFixed(4)); // 保留4位小数，避免浮点误差
          totalMoneyAll += item.moneyall;

        }
      });

      // 第二步：如果有错误，统一提示，不插入汇总行
      if (errors.length > 0) {
        this.$alert(
          `<div style="max-height: 400px; overflow-y: auto; font-size: 14px;">
        <p>以下 ${errors.length} 行数据不完整，无法计算小计金额：</p>
        <ul style="list-style: circle; padding-left: 20px;">
          ${errors.map(err => `<li>${err}</li>`).join('')}
        </ul>
      </div>`,
          '数据维护提示',
          {
            dangerouslyUseHTMLString: true,
            type: 'error',
            center: false,
            confirmButtonText: '确定'
          }
        );
        return;
      }

      // 第三步：插入汇总行
      if (totalMoneyAll > 0) {
        const insertData = [
          {
            material_name: '小计金额汇总',
            moneyall: parseFloat(totalMoneyAll.toFixed(2)),
            is_total: true, // 可用于样式区分
            // 其他字段可为空
          }
        ];
        $table.insertAt(insertData, -1);

        this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
        this.$message.success(`小计金额合计：${totalMoneyAll.toFixed(2)} 已插入`);
      } else {
        this.$message.warning('小计金额为 0，未插入汇总行。');
        return
      }
      this.enableCompute = true
    },
    /**
    * 成本合计：合并所有待确认行到一个弹窗，并显示完整行数据
    */
    async totalCostTotalCost() {
      const $table = this.$refs.xGrid;
      const tableData = this.$refs.xGrid.getTableData()?.fullData ?? [];
      //移除已存在的合计行（避免重复插入）
      if (tableData[tableData.length - 1]?.material_name === "合计") {
        this.$refs.xGrid.remove(tableData[tableData.length - 1]);
        // 关键：从数据源中也移除合计行（避免保存时携带）
        const totalRowIndex = tableData.findIndex(row => row.material_name === "合计");
        if (totalRowIndex > -1) {
          tableData.splice(totalRowIndex, 1);
        }
      }
      console.log('this.table', tableData)

      let totalCost = 0; // 单价成本总和
      let usage_cost2 = 0; // 用量成本总和
      const errors = [];
      const pendingRows = []; // 存储“单价空/无效且未标记无成本”的行

      //  收集所有符合条件的问题行
      for (let i = 0; i < tableData.length; i++) {
        const item = tableData[i];
        // 核心判断：
        // - 条件1：单价空/无效（costEmpty）
        // - 条件2：未标记为“无成本”（!isMarkedNoCost）
        const isMarkedNoCost = item.ORcost === '否' || item.ORcost === false || item.ORcost === 'false'; // 已标记“无成本”
        const cost = item.cost;
        const costEmptyOrInvalid = cost == null || cost === '' || isNaN(parseFloat(cost)); // 单价空/无效

        // 仅收集“单价空/无效 且 未标记无成本”的行
        if (costEmptyOrInvalid && !isMarkedNoCost) {
          pendingRows.push({
            index: i + 1, // 行号（从1开始）
            num: item.num || '—', // 物料编号
            name: item.name || '—', // 物料名称
            currentORcost: item.ORcost ?? '未设置', // 当前“是否无成本”标记状态
            ...item // 保留完整行数据，方便后续处理
          });
        }
      }

      //  弹窗提示所有问题行（
      if (pendingRows.length > 0) {
        const confirmMessage = `
      <div style="max-height: 400px; overflow-y: auto; font-size: 14px;">
        <p style="color: #ff4d4f; font-weight: bold;">以下 ${pendingRows.length} 行“单价成本为空/无效且未标记为无成本”，请处理：</p>
        <ul style="list-style: none; padding-left: 0; margin: 15px 0;">
          ${pendingRows
            .map(
              (row, idx) => `
              <li style="margin: 8px 0; padding: 8px; border-bottom: 1px dashed #ccc; background: #f9f9f9;">
                <strong>第 ${row.index} 行</strong>:
                <br>
                <small>
                  物料编号: ${row.num} | 
                  物料名称: ${row.name} | 
                  当前“是否无成本”标记: ${row.currentORcost}
                </small>
              </li>
            `
            )
            .join('')}
        </ul>
        <p style="font-size: 13px; color: #666;">请将上述行标记为“无成本”，或维护其单价成本数据。</p>
      </div>
    `;

        try {
          // 弹窗交互：罗列所有问题行，由用户确认
          await this.$confirm(confirmMessage, '待确认：无成本且未标记的行', {
            distinguishCancelAndClose: true,
            confirmButtonText: '我知道了，立即维护',
            cancelButtonText: '暂不处理', // 恢复取消按钮，让用户选择
            showCancelButton: true, // 显示取消按钮
            closeOnClickModal: false,
            type: 'warning',
            dangerouslyUseHTMLString: true,
            center: false
          });

          // 用户点击“立即维护”→ 将问题行转为错误列表提示
          pendingRows.forEach(row => {
            errors.push(`第 ${row.index} 行（物料编号：${row.num}）：单价空/无效且未标记无成本`);
          });

          // 触发错误提示（将所有问题行用文本提示）
          if (errors.length > 0) {
            // this.$message.error(`请处理以下问题行：\n${errors.join('\n')}`);
            return; // 终止后续流程，等待用户维护
          }

        } catch (action) {
          this.$message.info('已终止成本汇总，请先处理上述无成本且未标记的行。');
          return;
        }
      }

      // 计算用量成本（仅处理“未标记无成本+单价有效的行”）
      tableData.forEach(item => {
        const isMarkedNoCost = item.ORcost === '否' || item.ORcost === false || item.ORcost === 'false';
        const costValid = item.cost != null && item.cost !== '' && !isNaN(parseFloat(item.cost));
        const amount = item.amount || 0;

        if (!isMarkedNoCost && costValid) {
          item.usage_cost = parseFloat((parseFloat(item.cost) * parseFloat(amount)).toFixed(3));
        } else {
          item.usage_cost = '';
        }
      });

      //  统计总和（仅统计有效行）
      tableData.forEach(item => {
        const isMarkedNoCost = item.ORcost === '否' || item.ORcost === false || item.ORcost === 'false';
        const cost = item.cost;
        const usageCost = item.usage_cost;

        const costValid = cost != null && cost !== '' && !isNaN(parseFloat(cost));
        const usageCostValid = usageCost != null && usageCost !== '' && !isNaN(parseFloat(usageCost));

        if (!isMarkedNoCost && costValid && usageCostValid) {
          totalCost += parseFloat(cost) || 0;
          usage_cost2 += parseFloat(usageCost) || 0;
        }
      });
      //  插入合计行
      const formattedTotalCost = parseFloat(totalCost.toFixed(3));
      const formattedUsageCost = parseFloat(usage_cost2.toFixed(3));
      if (totalCost > 0) {
        var insertData = []
        insertData.push({ material_name: '合计', cost: formattedTotalCost, usage_cost: formattedUsageCost })
        tableData.push({
          material_name: '合计',
          cost: formattedTotalCost,
          usage_cost: formattedUsageCost
        });
        $table.insertAt(insertData, -1);
        this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
        this.iscounted = true
        console.log('成本合计中的iscounted', this.iscounted)
        // this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
        this.$message.success(`
      合计行已插入：<br>
      单价成本总计：${formattedTotalCost.toFixed(3)} 元<br>
      用量成本总计：${formattedUsageCost.toFixed(3)} 元
    `, { dangerouslyUseHTMLString: true });
      } else {
        this.$message.warning('没有有效的成本数据进行汇总。');
      }
    },
    async makeColumns() {
      console.log("aa")
      let flag = false
      const res = await request({
        method: 'post',
        url: '/rest/v1/formFunction/verifyUserPermissions',
        headers: {
          authorization: sessionStorage.getItem('authorization'),
          'Content-Type': 'application/json',
        },
        data: sessionStorage.getItem('userID')
        // data: '707281877790130176'
      });
      if (res.data.success) {
        if (this.widget.options.name === 'datatable67262' || this.widget.options.name === 'datatable70276') {
          if (res.data.userGroups.includes('硬件')) {

            this.yjshow = true

          }
          if (res.data.userGroups.includes('采购')) {
            flag = true
          }
        }
        if (this.widget.options.name === 'datatable37383') {
          if (res.data.userGroups.includes('结构')) {
            this.RJSHow = true
            console.log("asdad", this.RJSHow)

          }
        }

      }
      if (flag) {
        this.isCaigou()
      } else {
        const {
          showIndex,
          tableColumns,
          showCheckBox,
          operationButtons,
          buttonsColumnTitle,
          buttonsColumnWidth,
          buttonsColumnFixed,
          showButtonsColumn,
          readonly
        } = this.widget.options;
        const arr = [];
        // 获取所有下拉组件的枚举值选项
        const enumObj = await this.getSelectOptions();
        const widgetObj = { input: TyPlmInput, date: TyPlmTimeDate, select: TyPlmSelect };
        if (showCheckBox && !this.isReadMode) arr.push({ type: 'checkbox', width: 50, fixed: 'left' });
        if (showIndex) arr.push({ type: 'seq', width: 50, fixed: 'left' });
        tableColumns.forEach(({ field, title, width, fixed, align, formatter, sortable, show, render, edit, component, enum: emumData }) => {
          const column = { field, title, width, fixed, align, sortable, visible: show };
          // modify by nieyz 2024/10/22 业务规则设置表格只读时列禁止编辑
          if (!this.isReadMode && edit && component) {
            column.editRender = {};
            const render = ({ row, column }) => {
              const props = {
                modelValue: row[field],
                ['onUpdate:modelValue']: (value) => {
                  row[field] = component === 'date' ? moment(value).format(formatter || 'YYYY-MM-DD') : value;
                }
              };
              // 下拉组件传下拉选项参数
              if (component === 'select') {
                props.options = { list: emumData?.enumOid ? enumObj[emumData.enumOid] : emumData?.list };
              }
              if (formatter) {
                props.format = formatter;
              }
              return h(widgetObj[component], props);
            };
            column.slots = {
              // 获取显示值，默认显示只读态
              default: ({ row, column }) => this.getDisplayText(component, row, column, emumData, enumObj),
              edit: render
            };
          } else if (render) {
            column.editRender = {};
            column.slots = {
              default: ({ row, column }) => row[field],
              edit: ({ row, column }) => {
                const func = new Function('h', 'params', 'components', render);
                const components = this.$root.$.appContext.components;
                return func(
                  h,
                  {
                    modelValue: row[field],
                    readonly,
                    ['onUpdate:modelValue']: (value) => {
                      row[field] = value;
                    }
                  },
                  components
                );
              }
            };
          }
          if ((this.widget.options.name === 'datatable67262' || this.widget.options.name === 'datatable70276') && (field == 'cost' || field == 'usage_cost')) {
            if (this.yjshow) {
              arr.push(column)
            }
          } else if (this.widget.options.name === 'datatable37383' && (field == 'cost' || field == 'usage_cost')) {
            if (this.RJSHow) {
              arr.push(column)
            }

          } else {
            if (show) arr.push(column);
          }
        });
        if (showButtonsColumn && operationButtons.length && operationButtons.some((item) => !item.hidden)) {
          const column = { field: 'operate', title: buttonsColumnTitle, width: buttonsColumnWidth, fixed: buttonsColumnFixed };
          column.slots = {
            default: ({ row, rowIndex }) => {
              const obj = {};
              operationButtons
                .filter((item) => !item.hidden)
                .forEach(
                  ({ name, label, ...rest }) =>
                  (obj[name] = () => (
                    <el-button link {...rest} onClick={() => this.operateButtonsClick(name, rowIndex, row)}>
                      {' '}
                      {label}
                    </el-button>
                  ))
                );
              return <OperateBUttonsWrap>{obj}</OperateBUttonsWrap>;
            }
          };
          if ((this.widget.options.name === 'datatable67262' || this.widget.options.name === 'datatable70276') && (field == 'cost' || field == 'usage_cost')) {
            if (this.yjshow) {
              arr.push(column)
            }
          } else if (this.widget.options.name === 'datatable37383' && (field == 'cost' || field == 'usage_cost')) {
            if (this.RJSHow) {
              arr.push(column)
            }

          } else {
            if (show) arr.push(column);
          }

        }
        this.columns = arr;

      }
    },
    handleOnCreated() {
      if (!!this.widget.options.onCreated) {
        let customFunc = new Function(this.widget.options.onCreated);
        customFunc.call(this);
      }

    },
    async obtainCostInformation(param) {
      const $table = this.$refs.xGrid;
      // console.log(this.$refs.xGrid.getTableData())
      //   console.log('表单',this.$refs.xGrid.getTableData()?.fullData)
      const numArray = this.$refs.xGrid.getTableData()?.fullData?.map(item => item.num);
      let costData = []
      if (param === '硬件') {
        const res = await request({
          method: 'post',
          url: ' /rest/v1/formFunction/obtainCostInformation?user=' + sessionStorage.getItem('userID') + '&form=硬件',
          headers: {
            authorization: sessionStorage.getItem('authorization')
          },
          data: numArray
        });
        costData = res.data.Data;
        console.log('数据', costData)

        // 仅反写单价成本（cost），删除用量成本计算逻辑
        this.$refs.xGrid.getTableData()?.fullData.forEach(item => {
          const matchedCost = costData.find(cost => cost.ItemCode === item.num);
          item.cost = matchedCost ? matchedCost.RmbPrice : item.cost;
        });
      } else if (param === '结构') {
        const res = await request({
          method: 'post',
          url: ' /rest/v1/formFunction/obtainCostInformation?user=' + sessionStorage.getItem('userID') + '&form=结构',
          headers: {
            authorization: sessionStorage.getItem('authorization'),
            'Content-Type': 'application/json'
          },
          data: numArray
        });
        costData = res.data.Data;
        // 仅反写单价成本（cost），删除用量成本计算逻辑
        this.$refs.xGrid.getTableData()?.fullData.forEach(item => {
          const matchedCost = costData.find(cost => cost.ItemCode === item.num);
          item.cost = matchedCost ? matchedCost.RmbPrice : item.cost;
          // 【删除】原用量成本计算逻辑
          // if (matchedCost == 0 || matchedCost == '') {
          //   this.$message.error(item.num + '成本为0');
          // } else {
          //   item.usage_cost = item.cost * item.amount
          // }
        });
      }
    },
    async isShenZhen() {
      const {
        showIndex,
        tableColumns,
        showCheckBox,
        operationButtons,
        buttonsColumnTitle,
        buttonsColumnWidth,
        buttonsColumnFixed,
        showButtonsColumn,
        readonly
      } = this.widget.options;
      const arr = [];
      // 获取所有下拉组件的枚举值选项
      const enumObj = await this.getSelectOptions();
      const widgetObj = { input: TyPlmInput, date: TyPlmTimeDate, select: TyPlmSelect };
      if (showCheckBox && !this.isReadMode) arr.push({ type: 'checkbox', width: 50, fixed: 'left' });
      if (showIndex) arr.push({ type: 'seq', width: 50, fixed: 'left' });
      tableColumns.forEach(({ field, title, width, fixed, align, formatter, sortable, show, render, edit, component, enum: emumData }) => {
        const column = { field, title, width, fixed, align, sortable, visible: show };
        // modify by nieyz 2024/10/22 业务规则设置表格只读时列禁止编辑
        if (!this.isReadMode && edit && component) {
          column.editRender = {};
          const render = ({ row, column }) => {
            const props = {
              modelValue: row[field],
              ['onUpdate:modelValue']: (value) => {
                row[field] = component === 'date' ? moment(value).format(formatter || 'YYYY-MM-DD') : value;
              }
            };
            // 下拉组件传下拉选项参数
            if (component === 'select') {
              props.options = { list: emumData?.enumOid ? enumObj[emumData.enumOid] : emumData?.list };
            }
            if (formatter) {
              props.format = formatter;
            }
            return h(widgetObj[component], props);
          };
          column.slots = {
            // 获取显示值，默认显示只读态
            default: ({ row, column }) => this.getDisplayText(component, row, column, emumData, enumObj),
            edit: render
          };
        } else if (render) {
          column.editRender = {};
          column.slots = {
            default: ({ row, column }) => row[field],
            edit: ({ row, column }) => {
              const func = new Function('h', 'params', 'components', render);
              const components = this.$root.$.appContext.components;
              return func(
                h,
                {
                  modelValue: row[field],
                  readonly,
                  ['onUpdate:modelValue']: (value) => {
                    row[field] = value;
                  }
                },
                components
              );
            }
          };
        }

        if (this.widget.options.name === 'requisition' && field == 'ccdd_hz') {
          show = false
        }
        if (show) arr.push(column);
      });
      if (showButtonsColumn && operationButtons.length && operationButtons.some((item) => !item.hidden)) {
        const column = { field: 'operate', title: buttonsColumnTitle, width: buttonsColumnWidth, fixed: buttonsColumnFixed };
        column.slots = {
          default: ({ row, rowIndex }) => {
            const obj = {};
            operationButtons
              .filter((item) => !item.hidden)
              .forEach(
                ({ name, label, ...rest }) =>
                (obj[name] = () => (
                  <el-button link {...rest} onClick={() => this.operateButtonsClick(name, rowIndex, row)}>
                    {' '}
                    {label}
                  </el-button>
                ))
              );
            return <OperateBUttonsWrap>{obj}</OperateBUttonsWrap>;
          }
        };

        if (this.widget.options.name === 'requisition' && field == 'ccdd_hz') {
          show = false
        }
        if (show) arr.push(column);
      }
      this.columns = arr;
    },

    async isCaigou() {
      const {
        showIndex,
        tableColumns,
        showCheckBox,
        operationButtons,
        buttonsColumnTitle,
        buttonsColumnWidth,
        buttonsColumnFixed,
        showButtonsColumn,
        readonly
      } = this.widget.options;
      const arr = [];
      // 获取所有下拉组件的枚举值选项
      const enumObj = await this.getSelectOptions();
      const widgetObj = { input: TyPlmInput, date: TyPlmTimeDate, select: TyPlmSelect };
      if (showCheckBox && !this.isReadMode) arr.push({ type: 'checkbox', width: 50, fixed: 'left' });
      if (showIndex) arr.push({ type: 'seq', width: 50, fixed: 'left' });
      tableColumns.forEach(({ field, title, width, fixed, align, formatter, sortable, show, render, edit, component, enum: emumData }) => {
        const column = { field, title, width, fixed, align, sortable, visible: show, };
        // modify by nieyz 2024/10/22 业务规则设置表格只读时列禁止编辑
        if (!this.isReadMode && edit && component) {
          column.editRender = {};
          const render = ({ row, column }) => {
            const props = {
              modelValue: row[field],
              ['onUpdate:modelValue']: (value) => {
                row[field] = component === 'date' ? moment(value).format(formatter || 'YYYY-MM-DD') : value;
              }
            };
            // 下拉组件传下拉选项参数
            if (component === 'select') {
              props.options = { list: emumData?.enumOid ? enumObj[emumData.enumOid] : emumData?.list };
            }
            if (formatter) {
              props.format = formatter;
            }
            return h(widgetObj[component], props);
          };
          column.slots = {
            // 获取显示值，默认显示只读态
            default: ({ row, column }) => this.getDisplayText(component, row, column, emumData, enumObj),
            edit: render
          };
        } else if (render) {
          column.editRender = {};
          column.slots = {
            default: ({ row, column }) => row[field],
            edit: ({ row, column }) => {
              const func = new Function('h', 'params', 'components', render);
              const components = this.$root.$.appContext.components;
              return func(
                h,
                {
                  modelValue: row[field],
                  readonly,
                  ['onUpdate:modelValue']: (value) => {
                    row[field] = value;
                  }
                },
                components
              );
            }
          };
        }

        if ((this.widget.options.name === 'datatable70276' || this.widget.options.name === 'datatable67262') && field == 'usage_cost') {
          show = false
          console.log('是datatable70276 或者datatable67262 切 field是 usage_cost')
        }
        if ((this.widget.options.name === 'datatable70276' || this.widget.options.name === 'datatable67262') && field == 'cost') {

          console.log('是cost' + show)
        }

        if (this.widget.options.name === 'datatable37383' && (field == 'usage_cost' || field == 'cost')) {
          show = false
        }

        if (show) arr.push(column);

      });
      if (showButtonsColumn && operationButtons.length && operationButtons.some((item) => !item.hidden)) {
        const column = { field: 'operate', title: buttonsColumnTitle, width: buttonsColumnWidth, fixed: buttonsColumnFixed };
        column.slots = {
          default: ({ row, rowIndex }) => {
            const obj = {};
            operationButtons
              .filter((item) => !item.hidden)
              .forEach(
                ({ name, label, ...rest }) =>
                (obj[name] = () => (
                  <el-button link {...rest} onClick={() => this.operateButtonsClick(name, rowIndex, row)}>
                    {' '}
                    {label}
                  </el-button>
                ))
              );
            return <OperateBUttonsWrap>{obj}</OperateBUttonsWrap>;
          }
        };

        if ((this.widget.options.name === 'datatable70276' || this.widget.options.name === 'datatable67262') && field == 'usage_cost') {
          show = false
        }
        if (this.widget.options.name === 'datatable37383' && (field == 'usage_cost' || field == 'cost')) {
          show = false
        }


        if (show) arr.push(column);
      }

      this.columns = arr;

    },
    async isHuiZhou() {
      const {
        showIndex,
        tableColumns,
        showCheckBox,
        operationButtons,
        buttonsColumnTitle,
        buttonsColumnWidth,
        buttonsColumnFixed,
        showButtonsColumn,
        readonly
      } = this.widget.options;
      const arr = [];
      // 获取所有下拉组件的枚举值选项
      const enumObj = await this.getSelectOptions();
      const widgetObj = { input: TyPlmInput, date: TyPlmTimeDate, select: TyPlmSelect };
      if (showCheckBox && !this.isReadMode) arr.push({ type: 'checkbox', width: 50, fixed: 'left' });
      if (showIndex) arr.push({ type: 'seq', width: 50, fixed: 'left' });
      tableColumns.forEach(({ field, title, width, fixed, align, formatter, sortable, show, render, edit, component, enum: emumData }) => {
        const column = { field, title, width, fixed, align, sortable, visible: show, };
        // modify by nieyz 2024/10/22 业务规则设置表格只读时列禁止编辑
        if (!this.isReadMode && edit && component) {
          column.editRender = {};
          const render = ({ row, column }) => {
            const props = {
              modelValue: row[field],
              ['onUpdate:modelValue']: (value) => {
                row[field] = component === 'date' ? moment(value).format(formatter || 'YYYY-MM-DD') : value;
              }
            };
            // 下拉组件传下拉选项参数
            if (component === 'select') {
              props.options = { list: emumData?.enumOid ? enumObj[emumData.enumOid] : emumData?.list };
            }
            if (formatter) {
              props.format = formatter;
            }
            return h(widgetObj[component], props);
          };
          column.slots = {
            // 获取显示值，默认显示只读态
            default: ({ row, column }) => this.getDisplayText(component, row, column, emumData, enumObj),
            edit: render
          };
        } else if (render) {
          column.editRender = {};
          column.slots = {
            default: ({ row, column }) => row[field],
            edit: ({ row, column }) => {
              const func = new Function('h', 'params', 'components', render);
              const components = this.$root.$.appContext.components;
              return func(
                h,
                {
                  modelValue: row[field],
                  readonly,
                  ['onUpdate:modelValue']: (value) => {
                    row[field] = value;
                  }
                },
                components
              );
            }
          };
        }
        if (this.widget.options.name === 'requisition' && field == 'ccdd_sz') {
          show = false
        }

        if (show) arr.push(column);

      });
      if (showButtonsColumn && operationButtons.length && operationButtons.some((item) => !item.hidden)) {
        const column = { field: 'operate', title: buttonsColumnTitle, width: buttonsColumnWidth, fixed: buttonsColumnFixed };
        column.slots = {
          default: ({ row, rowIndex }) => {
            const obj = {};
            operationButtons
              .filter((item) => !item.hidden)
              .forEach(
                ({ name, label, ...rest }) =>
                (obj[name] = () => (
                  <el-button link {...rest} onClick={() => this.operateButtonsClick(name, rowIndex, row)}>
                    {' '}
                    {label}
                  </el-button>
                ))
              );
            return <OperateBUttonsWrap>{obj}</OperateBUttonsWrap>;
          }
        };

        if (this.widget.options.name === 'requisition' && field == 'ccdd_sz') {
          show = false
        }

        if (show) arr.push(column);
      }

      this.columns = arr;
    },


    handleOnMounted() {
      if (!!this.widget.options.onMounted) {
        let customFunc = new Function(this.widget.options.onMounted);
        customFunc.call(this);
      }
    },
    // 获取表单所有下拉组件的下拉选项
    async getSelectOptions() {
      const enumDefKeys = this.widget.options.tableColumns.reduce((pre, cur) => {
        if (cur.edit && cur.enum?.enumOid && !pre.includes(cur.enum.enumOid)) {
          pre.push(cur.enum.enumOid);
        }
        return pre;
      }, []);
      if (!enumDefKeys.length) return;
      const res = await request({
        method: 'post',
        url: '/rest/v1/enum/getEnumItemsMap',
        data: {
          enumDefKeys
        }
      });
      if (res?.data?.success) {
        const data = res.data.data;
        const enumObj = {};
        Object.keys(data).forEach((key) => {
          // modify by nieyz 2025/4/10 修复下拉组件的选项值
          enumObj[key] = Object.keys(data[key]).map((item) => ({ label: data[key][item], value: item }));
        });
        return enumObj;
      }
      return {};
    },
    /**
     * 获取编辑组件的显示值
     * @author nieyz
     * @Date 2025-6-20
     * @param component 组件
     * @param row 行数据
     * @param column 列对象
     * @param emumData 组件枚举对象
     * @param enumObj 所有枚举的数据集合
     */
    getDisplayText(component, row, column, emumData, enumObj) {
      const value = row[column.field];
      if (component === 'select') {
        const optionList = emumData?.enumOid ? enumObj[emumData.enumOid] : emumData?.list || [];
        return optionList.find((item) => item.value == value)?.label || (value ?? '');
      }
      return value;
    },

    sumNum(list = [], field) {
      let count = 0;
      list.forEach((item) => {
        count += Number(item[field]);
      });
      return count;
    },
    footerMethod({ columns, data }) {
      const arr = columns.map((column, _columnIndex) => {
        if (_columnIndex === 0) {
          return '合计';
        }
        const item = this.widget.options.tableColumns.find((each) => each.field === column.field);
        if (item && item.sum) {
          return this.sumNum(data, column.field);
        }
        return null;
      });
      return [arr];
    },
    async copyRow(row) {
      const record = cloneDeep(row);
      const $table = this.$refs.xGrid;
      const { row: newRow } = await $table.insertAt(record, row);
      await $table.setEditCell(newRow);
    },
    //因升版至HF37,方法冲突注释
    // async insertEvent() {
    //   const $table = this.$refs.xGrid;
    //   if (!$table) return;
    //   // modify by nieyz 2025/1/22 配置高级查询来添加数据时出现新增弹窗，否则直接添加行数据
    //   if (['1', '2'].includes(this.widget.options.datasourceType)) return (this.showDialog = true);
    //   const record = {};
    //   $table.insertAt(record, -1); // 插入到最后
    //   // modify by nieyz 2024/10/22 修改表单赋值逻辑
    //   this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
    // },
    async insertEvent() {
      console.log("新增")
      const e = this.$refs.xGrid;
      if (!e)
        return;
      if (["1", "2"].includes(this.widget.options.datasourceType))
        return this.showDialog = !0;

      const t = {
        _X_ROW_KEY: this.$nanoid()
      };
      e.insertAt(t, -1),
        this.globalModel.formModel[this.widget.options.name] = e.getTableData()?.fullData || []
    },

    importData() {
      const $table = this.$refs.xGrid;
      if ($table) {
        $table.importData();
        // modify by nieyz 2024/10/22 修改表单赋值逻辑
        this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
      }
    },

    formatter(row, column, cellValue) {
      return cellValue;
    },
    handlePageSizeChange(pageSize) {
      //
    },
    handleCurrentPageChange(currentPage) {
      //
    },
    operateButtonsClick(buttonName, rowIndex, row) {
      const func = new Function('buttonName', 'rowIndex', 'row', this.widget.options.onOperationButtonClick);
      func(buttonName, rowIndex, row);
    },

    /**
     * @description 从对象中取属性的值,区分IBA与普通属性
     * @author nieyz
     * @Date 2025-4-14
     * @param { object } row 对象数据
     * @param { string } propsKey 属性名称
     */
    getPropertyValue(row, propsKey) {
      // IBA属性从对象中取值
      if (propsKey.startsWith('iba_')) {
        const key = propsKey.split('iba_')[1];
        return row.ibaAttrMapForSearch ? row.ibaAttrMapForSearch[key] || '' : '';
      }
      // 有真值时取真值, 有额外值时取额外值
      return row[propsKey] ? row[propsKey] : row.extAttrMapForSearch ? row.extAttrMapForSearch[propsKey] || '' : '';
    },
    // 将对象选择绑定的映射关系解析成对应值
    transSpanToValue(htmlString, row) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(htmlString, 'text/html');
      const spans = doc.querySelectorAll('span');
      spans.forEach((span) => {
        // 获取span的父节点
        const parent = span.parentNode;
        const propsKey = span.getAttribute('value');
        // modify by nieyz 2025/4/14 将span的内容添加到父节点中，并移除span标签, iba属性取值要特殊处理
        parent.replaceChild(document.createTextNode(`${this.getPropertyValue(row, propsKey) || ''}`), span);
      });
      return doc.body.innerText;
    },
    transRowToModel(row) {
      const obj = { oid: row.oid, branchid: row.branchid, otype: row.otype };
      this.widget.options.objectSelectData?.attrMap?.map(({ props, attr, widgetType }) => {
        obj[props] = this.transSpanToValue(attr, row);
      });
      return obj;
    },
    async confirmFunc(data = []) {
      // modify by nieyz 2025/8/2 丁龙豪修改导入时逻辑
      const $table = this.$refs.xGrid;
      if ($table && data?.length) {
        var insertData = data.map((row) => this.transRowToModel(row));
        if (this.widget.options.label === 'beijingse' || this.widget.options.label === 'jiegoujian') {
          console.log("shouye")
          try {
            console.log('beijingse||jiegoujian')
            //  insertData[0].num = '104110336AB';
            const res = await request({
              method: 'get',
              url: '/rest/v1/formFunction/addFormDataSingle?itemCode=' + insertData[0].num,
              headers: {
                authorization: sessionStorage.getItem('authorization')
              }
            }).then((res) => {
              const data2 = res.data.data;
              insertData[0].type = data2.u9_item_sPECS;
              insertData[0].life = data2.lifecycleState;
              insertData[0].amount = data2.storeQty;
              //insertData[0].purchase_time = element.batchPurchaseDeliveryDate; //采购交期
              // insertData[0].location = element.areference //位置
              // insertData[0].ORcost = element.isCost  //是否有成本
              insertData[0].purchase_time = data2.batchPurchaseDeliveryDate; //采购交期
              insertData[0].cgfzr = data2.cgfzr   // 采购负责人
              insertData[0].location = data2.areference //位置
              insertData[0].ORcost = data2.isCost  //是否有成本
              insertData[0].cgfzr = data2.cgfzr  //是否有成本

              // modify by nieyz 2024/10/22 修改表单赋值逻辑
              this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
            });
          } catch (error) {
            console.log(error);
          }

          $table.insertAt(insertData, -1);
          this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
        } else if (this.widget.options.label === 'gongguan') {
          console.log("gongguan")
          try {
            //  insertData[0].num = '20135036100';
            data = [insertData[0].P_number]
            const res = await request({
              method: 'post',
              url: '/rest/v1/formFunction/addFormDataStore',
              data: data,
              headers: {
                authorization: sessionStorage.getItem('authorization')
              }
            }).then((res) => {
              const data2 = res.data.data;

              for (let index = 0; index < data2.length; index++) {
                const element = data2[index];
                console.log(element)
                insertData[0].P_number = element.objectNumber;
                insertData[0].P_name = element.name;
                insertData[0].P_size = element.u9_item_sPECS;
                insertData[0].storeQty = element.StoreQty;
                insertData[0].get_stock_time = element.getStockTime;
                insertData[0].old_p_ship = element.ShipQty12;
                insertData[0].Months_order = element.SoQty5;
                insertData[0].expect_Months = element.UseMonths
                insertData[0].ORcost = element.isCost  //是否有成本
                insertData[0].cgfzr = element.cgfzr

                $table.insertAt(insertData, -1);
                this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
                // modify by nieyz 2024/10/22 修改表单赋值逻辑
              }

            });
          } catch (error) {
            console.log(error);
          }

        }
        else if (this.widget.options.label === 'head-table-ding') {
          console.log("head-table-ding")
          if (this.widget.options.name === 'requisition') {
            console.log('insertaaa', insertData)
            try {
              const res = await request({
                method: 'post',
                url: '/rest/v1/formFunction/addFormDataPurchase',
                data: insertData[0].num,  // 直接发送字符串数据
                headers: {
                  authorization: sessionStorage.getItem('authorization'),  // 认证头部
                  'Content-Type': 'text/plain',  // 设置为纯文本格式
                }
              }).then((res) => {
                const data2 = res.data.data;
                for (let index = 0; index < data2.length; index++) {
                  const element = data2[index];
                  insertData[0].num = element.objectNumber;
                  insertData[0].name = element.name;
                  insertData[0].type = element.u9_item_sPECS;
                  insertData[0].life = element.lifecycleState; //生命周期
                  insertData[0].stock = element.storeQty; //库存
                  insertData[0].amount = element.u9_BOMComponent_UsageQty; //用量
                  insertData[0].purchase_time = element.batchPurchaseDeliveryDate; //采购交期
                  insertData[0].location = element.areference //位置
                  insertData[0].unit = element.defaultunitkey //单位
                  insertData[0].unitPrice = element.unitPrice    //单价
                  insertData[0].ORcost = element.isCost  //是否有成本
                  insertData[0].cgfzr = element.cgfzr
                  $table.insertAt(insertData, -1);
                  this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
                  //  this.syncTableDataCopy();


                  // this.enablePriceWatch = true
                }
              });
            } catch (error) {
              console.log(error);
            }
          }
          else {
            try {
              const res = await request({
                method: 'get',
                url: '/rest/v1/formFunction/addFormDataMany?itemCode=' + insertData[0].num,
                headers: {
                  authorization: sessionStorage.getItem('authorization')
                }
              }).then((res) => {
               
                console.log('iscount', this.iscounted)
                if (this.iscounted) {
                  console.log('进来了')
                  const tableData = this.$refs.xGrid.getTableData()?.fullData ?? [];
                  //  移除已存在的合计行（避免重复插入）
                  if ( tableData[ tableData.length - 1]?.material_name === "合计") {
                    this.$refs.xGrid.remove( tableData[ tableData.length - 1]);
                    // 关键：从数据源中也移除合计行（避免保存时携带）
                    const totalRowIndex =  tableData.findIndex(row => row.material_name === "合计");
                    if (totalRowIndex > -1) {
                       tableData.splice(totalRowIndex, 1);
                    }
                     
                  }
                  console.log("前数据", tableData)
                }
                const data2 = res.data.data;
                console.log('data2', data2)
                // console.log("lkankan", insertData)
                for (let index = 0; index < data2.length; index++) {
                  const element = data2[index];
                  insertData[0].num = element.objectNumber;
                  insertData[0].name = element.name;
                  insertData[0].type = element.u9_item_sPECS;
                  insertData[0].life = element.lifecycleState; //生命周期
                  insertData[0].stock = element.storeQty; //库存
                  insertData[0].amount = element.u9_BOMComponent_UsageQty; //用量
                  insertData[0].purchase_time = element.batchPurchaseDeliveryDate; //采购交期
                  insertData[0].location = element.areference //位置
                  insertData[0].unit = element.defaultunitkey //单位
                  insertData[0].ORcost = element.isCost  //是否有成本
                  insertData[0].cgfzr = element.cgfzr
                  insertData[0].iscjl = element.iscjl
                  insertData[0].substituteMaterialInfo = element.substituteMaterialInfo
                  $table.insertAt(insertData, -1);

                  this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
                  console.log("数据", this.globalModel.formModel[this.widget.options.name])
                  
                }
                this.iscounted = false
              });
            } catch (error) {
              console.log(error);
            }
          }

        } else {
          console.log("qita")
          if (this.widget.options.name === 'datatable84226') {
            console.log('insertData22', insertData)
            let itemCodeList = []
            itemCodeList = insertData.map((item) => {
              return item.number
            }).join(',')
            console.log("itemCodeList", itemCodeList)
            try {
              const res = await request({
                method: 'get',
                url: '/rest/v1/formFunction/queryStockInfo',
                params: {
                  itemCodeList
                },
                headers: {
                  authorization: sessionStorage.getItem('authorization'),  // 认证头部
                }
              }).then((res) => {
                const data2 = res.data.data;
                console.log('data2Life', data2)
                for (let index = 0; index < data2.length; index++) {
                  const element = data2[index];
                  insertData[0].org_name = element.org_name;  //组织名称
                  insertData[0].number = element.number; // 品号
                  insertData[0].name = element.name; // 品名
                  insertData[0].specification = element.specification; //规格
                  insertData[0].life = element.life; //料品生命状态
                  insertData[0].storage_location = element.storage_location; //存储地点
                  insertData[0].life_head = element.life_head; //料品负责人
                  insertData[0].inventory_stock = element.inventory_stock //库存量
                  $table.insertAt(insertData[0], -1);
                  this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
                }
              });
            } catch (error) {
              console.log(error);
            }
          }
          else {
            $table.insertAt(insertData, -1);
            this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
          }
        }
        this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.fullData || [];
        // console.log("方法", $table.insertAt)
      }
    }
  }
};
</script>
<style scoped>
.search-container {
  display: flex;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

::v-deep .highlight-row {
  background-color: #e6f7ff !important;
  /* 使用更明显的浅蓝色 */
  color: #1890ff !important;
  /* 同时改变文字颜色 */
}

.modal-content {
  margin: 20px 0;
}

.input-field {
  margin-top: 15px;
}

.cancel-btn {
  border-color: #ff4d4f;
  color: #ff4d4f;
}

.cancel-btn:hover {
  background-color: #fff1f0;
}
</style>